UITableViewHeaderFooterView复用

1.首先要自定义一个sectionHeadView/sectionFootView继承自 UITableViewHeaderFooterView,如下:

1
2
3
4
5
#import <UIKit/UIKit.h>

@interface CircleHeaderFooterView : UITableViewHeaderFooterView

@end

2.在自定义的sectionHeadView/sectionFootView中重写这个方法,设置复用

1
2
3
4
5
6
7
8
9
10
11
12
13
#import "CircleHeaderFooterView.h"

@implementation CircleHeaderFooterView

-(instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithReuseIdentifier:reuseIdentifier];
if (self) {
//表示初始化方法
}
return self;
}
@end

3.在需要调用自定义sectionHeadView/sectionFootView的VC里面调用table的代理方法,用法跟cell的复用相似

1
2
3
4
5
6
7
8
9
10
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
static NSString *viewIdentfier = @"headView";
CircleHeaderFooterView *sectionHeadView = [tableViewdequeueReusableHeaderFooterViewWithIdentifier:viewIdentfier];
if(!sectionHeadView){
sectionHeadView = [[CircleHeaderFooterView alloc]initWithReuseIdentifier:viewIdentfier];
sectionHeadView.contentView.backgroundColor = [UIColor whiteColor];
}
return sectionHeadView;
}

新写法

c
1
2
3
4
5
6
7
8
9
10
1:注册headerView
[self.tableView registerClass:[CircleHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"section"];

2:使用
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
CircleHeaderFooterView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"section"];
headView.textLabel.text = [NSString stringWithFormat:@"section %ld", section];
return headView;
}

系统自带

1
2
3
4
5
6
7
8
9
10

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UITableViewHeaderFooterView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"section"];
if (!headView) {
headView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"section"];
}
headView.textLabel.text = [NSString stringWithFormat:@"section %ld", section];
return headView;
}
文章作者: kyren
文章链接: http://huluo666.github.io/2016/05/29/UITableViewHeaderFooterView 复用/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Kyren's Blog